package com.njupt.order.interceptor;

import com.njupt.common.pojo.CookieUtils;
import com.njupt.common.pojo.TaotaoResult;
import com.njupt.pojo.TbUser;
import com.njupt.sso.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 16:16 2018/6/5
 * @Modified By:
 **/
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${TOKEN_KEY}")
    private String TOKEN_KEY;
    @Value("${SSO_LOGIN_URL}")
    private String SSO_LOGIN_URL;
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //执行Handler之前执行此方法
        // a)从cookie中取token。
        String token = CookieUtils.getCookieValue(request,TOKEN_KEY);
        //b)没有token，需要跳转到登录页面。
        if (StringUtils.isBlank(token)){
            //获取当前请求的URL
            String redirecturl = request.getRequestURL().toString();
            response.sendRedirect(SSO_LOGIN_URL+"/page/login"+"?reidrect="+redirecturl);
            //拦截
            return false;
        }
        //c)有token。调用sso系统的服务，根据token查询用户信息。
        TaotaoResult result = userService.getUserByToken(token);
        //d)如果查不到用户信息。用户登录已经过期。需要跳转到登录页面。
        if (result.getStatus()!=200){
            //获取当前请求的URL
            String redirecturl = request.getRequestURL().toString();
            //b)没有token，需要跳转到登录页面。
            response.sendRedirect(SSO_LOGIN_URL+"/page/login"+"?reidrect="+redirecturl);
            //拦截
            return false;

        }

        //e)查询到用户信息。放行。
        TbUser user = (TbUser) result.getData();
        request.setAttribute("user",user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
